package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"
	"taskschedu/master/monitor"
	"taskschedu/master/schedutask"
	"taskschedu/master/workerpool"

	"github.com/gin-gonic/gin"
)

var retryCount = 3

func main() {
	// 启动worker发现服务
	err := workerpool.StartWorkerDiscovery("^worker-.*")
	if err != nil {
		log.Fatalf("启动worker发现服务失败: %v", err)
	}
	// 确保在程序退出时停止worker发现服务
	defer workerpool.StopWorkerDiscovery()

	// 启动HTTP API服务
	r := gin.Default()
	r.POST("/task", schedutask.SubmitTask)
	r.GET("/task/:id", schedutask.GetTask)
	go schedutask.ScheduleTask(retryCount)

	// 启动prometheus监控接口
	go monitor.StartMonitor()

	// 优雅关闭
	go func() {
		sigChan := make(chan os.Signal, 1)
		signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
		<-sigChan
		log.Println("正在关闭服务...")
		os.Exit(0)
	}()

	// 启动HTTP服务
	log.Println("Master HTTP服务启动在 :8080")
	r.Run(":8080")
}
